/*
 * EmailNotificationJob.java
 *
 * Created on February 6, 2009, 5:00 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.vacuela.phonecredits;

import com.vacuela.phonecredits.util.SynchUtils;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

/**
 *
 * @author nestor.carrasco
 */
public class EmailNotificationJob implements Job {
     protected final Log log = LogFactory.getLog(getClass());
    SynchUtils syn  = null;
  
    
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("Start Mail Join =>>>" + new Date());
        try {
            log.info("++++++++++++++++++++++++++++++++++");
            log.info("++++++++++++++++++++++++++++++++++");
            syn = (SynchUtils)jobExecutionContext.getScheduler().getContext().get("utilClass");
            syn.createFile();       
            String[] mails = syn.getEmailsList().split(";");  
            mailerEtor(mails);
            log.info("++++++++++++++++++++++++++++++++++");
            log.info("++++++++++++++++++++++++++++++++++");
            
        }catch(Exception e ){
            e.printStackTrace();
        }finally{
          //  syn.closeConnection();
        }
           log.info("Finish Mail Join =>>>" + new Date());
    }
    
    private   void mailerEtor(String[] mmail) throws AddressException, MessagingException{
        log.info("Setting the Email Parameter");
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.debug", "true");
        props.put("mail.smtp.socketFactory.port", syn.getConfigParam("puerto"));
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.auth", "true");
        if ("TRUE".equalsIgnoreCase(syn.getConfigParam("proxyEnabled"))){
            System.getProperties().put("proxySet", "true");
            System.getProperties().put("http.proxyHost", syn.getConfigParam("proxyIP"));
            System.getProperties().put("http.proxyPort", syn.getIntConfigParam("proxyPort"));
            
        }
        
        
        InternetAddress[] address = new InternetAddress[mmail.length];
        try {
            log.info("Creating the Session");
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(false);
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(syn.getConfigParam("fromMail")));
            msg.setSubject("PhoneCredits App");
            log.info("Emails => " + mmail);
            for (int i = 0; i < mmail.length; i++) {
                address[i] = new InternetAddress(mmail[i]);
            }
            msg.saveChanges();
            msg.setSentDate(new Date());
            //
            setFileAsAttachment(msg,syn.getConfigParam("pathFile"));
            msg.saveChanges();
            //
            Transport transport = session.getTransport("smtp");
            transport.connect(syn.getConfigParam("smtpServer"),  syn.getConfigParam("fromMail"), syn.getConfigParam("pass"));
            log.info("Sending Email");
            transport.sendMessage(msg, address);
            
            transport.close();
            
        } catch (Exception mex) {
            log.info("Exception durin Send Email" + mex);
        }
        
    }
    
    private  void setFileAsAttachment(Message msg, String filename)
    throws MessagingException {
        
        log.info("Attaching the File");
        MimeBodyPart p1 = new MimeBodyPart();
        p1.setText(syn.getConfigParam("mensaje"));
        
        // Create second part
        MimeBodyPart p2 = new MimeBodyPart();
        
        // Put a file in the second part
        FileDataSource fds = new FileDataSource(filename);
        p2.setDataHandler(new DataHandler(fds));
        p2.setFileName(fds.getName());
        
        // Create the Multipart.  Add BodyParts to it.
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(p1);
        mp.addBodyPart(p2);
        
        // Set Multipart as the message's content
        msg.setContent(mp);
        log.info("Finish Attached");
    }
    
    public static void main(String[] args){
        try {
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            JobDetail jd = new JobDetail("JobTest","group1",EmailNotificationJob.class);
            //CronTrigger ct = new CronTrigger("cronTest","group2","0 0/1");
            
            long startTime = System.currentTimeMillis() + 3000L;
            SimpleTrigger simple = new SimpleTrigger("myTrigger",
                    "group1",
                    new Date(startTime),
                    new Date(startTime + (1000 * 60 *5)),
                    0,
                    0L);
            SynchUtils syn = new SynchUtils();
            syn.openConnection();
            sched.scheduleJob(jd,simple);
            
            sched.getContext().put("utilClass",syn);
            sched.start();
            //PhoneSynchronizerJob job = new PhoneSynchronizerJob();
            //JobExecutionContext context = new JobExecutionContext(sched,null,jd);
            //context.put("utilClass",syn);
            //job.execute(context);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
